const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatTime2 = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}

const formatDate = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()


    return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}


module.exports = {
    formatTime: formatTime,
    formatTime2: formatTime2,
    formatDate: formatDate,


    initBluetooth: initBluetooth,
    stopBluetoothFond: stopBluetoothFond,
    connToDid: connToDid,

    connectTO: connectTO,
    closeconn: closeconn,

    closeBLEConnection: closeBLEConnection,
    getServices: getServices,
    sendMsg: sendMsg,
    ab2hex: ab2hex,
    ab2Ascii: ab2Ascii,
    strToHexCharCode: strToHexCharCode,


    readMsg: readMsg,
    onBLEState: onBLEState,
    ctof: ctof,
    ftoc: ftoc,
    handleData: handleData,



}
var app = getApp()

// ===============蓝牙模块=======================


// 初始化蓝牙适配器
function initBluetooth() {
    //将缓存的设备信息清空
    app.globalData.equs = []
    console.log(app.globalData.equs)


    console.log("===>>初始化蓝牙适配器")
    var that = this;
    if (!wx.openBluetoothAdapter) {
        console.log('蓝牙适配器打开失败，请检查微信版本或手机是否支持小程序蓝牙模块！')
    } else {
        console.log("===>>蓝牙适配器打开成功")
        wx.openBluetoothAdapter({
            success: function (res) {
                // that.setData({
                //     msg: "初始化蓝牙适配器成功！"
                // })
                console.log("===>>获取本机蓝牙适配器状态")
                wx.getBluetoothAdapterState({ //获取本机蓝牙适配器状态
                    success: function (res) {
                        console.log('==>>本机蓝牙适配器状态：')
                        console.log(res)


                        //搜索设备
                        searchBluetooth()

                    }
                })
            },
            fail: function (err) {
                // console.log(err)
                console.log("===>>初始化蓝牙适配器失败")
                wx.showToast({
                    title: '初始化蓝牙适配器失败！',
                    icon: 'none',
                    duration: 3000
                })

            }
        })
    }
}

//搜索获取已发现设备
function searchBluetooth() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({ //开始搜寻附近的蓝牙外围设备
        success: function (res) {
            console.log('搜索周边蓝牙设备，==>>搜索成功')
            console.log(res)
            wx.getBluetoothDevices({ //sucess返回uuid 对应的的已连接设备列表，Array类型
                success: function (res) {
                    console.log('===============搜索出来的蓝牙设备列表')
                    console.log(res)
                    //是否有已连接设备
                    wx.getConnectedBluetoothDevices({ ////根据 uuid 获取处于已连接状态的设备
                        success: function (res) {
                            console.log('已连接的蓝牙设备:')
                            console.log(JSON.stringify(res.devices));

                            // that.setData({
                            //     connectedDeviceId: res.deviceId
                            // })
                        }
                    })
                    // that.setData({
                    //     devices: res.devices,
                    // })

                    console.log('====>>更新设备信息')

                    updateEqu(res.devices)

                },
                fail(err) {
                    console.log('err==2>>' + err)
                }
            })
        },
        fail(err) {
            console.log('err==1>>' + err)
        }
    })

    //监听寻找到新设备的事件
    wx.onBluetoothDeviceFound(function (res) {
        var devices = res.devices;
        console.log('发现新设备==++++++++')

        if (devices[0].name == "IR-8A") {
            console.log(devices[0])


            let mac1 = ab2hex(devices[0].advertisData).toUpperCase()
            let mac2 = app.globalData.equ.mac.replace(/:/g, '')
            console.log('mac1:'+mac1)
            console.log('mac2:'+mac2)

            if (mac1.indexOf(mac2) > -1) {
                app.globalData.equ.deviceId = devices[0].deviceId

                wx.setStorageSync('equdid', app.globalData.equ.deviceId)

            }

        }


        //追加设备列表
        app.globalData.equs = app.globalData.equs.concat(devices)

        console.log(app.globalData.equs)

        console.log('==++++++++')

    })

}

function stopBluFund() {
}


function connToDid() {
    var that = this
    let mac = app.globalData.equ.deviceId
    app.globalData.ewBluetooth.deviceId = app.globalData.equ.deviceId
    if (app.globalData.isA) {
        app.globalData.ewBluetooth.deviceId = app.globalData.equ.mac

        mac = app.globalData.equ.mac
    }

    console.log('====>>mac:' + mac)
    connectTO(mac, function (res) {
        if (res) {
            console.log('连接设备成功？？' + res)
            app.globalData.equconn0 = true
            stopBluetoothFond()

            wx.onBLEConnectionStateChange(function (res) {
                console.log("监听蓝牙连接状态: " + JSON.stringify(res));
                // 该方法回调中可以用于处理连接意外断开等异常情况
                console.log(`设备： ${res.deviceId}  的连接状态: ${res.connected}`)
                if (!res.connected) {
                    console.log('======================>>>>连接已断开')
                    app.globalData.equconn0 = false

                }
            })


            getServices(mac, function (res) {
                console.log('===========>>>获取服务回调')
                console.log(res)
                onBLEState() //启用notify
                var time = new Date().getTime()
                time = parseInt(time / 1000)
                console.log(time)

                //连接成功后发送时间
                let str1 = 'IR8A+A1,t=' + time
                let str2 = 'IR8A+A2,'
                let str3 = 'IR8A+A3,'

                //连接成功后发送当前用户ID
                let str4 = 'IR8A+A4,userid=' + app.globalData.usersIndex
                let str6 = 'IR8A+A6,'

                sendMsg(str1, function (res) {
                    sendMsg(str2, function (res) {
                        sendMsg(str3, function (res) {
                            sendMsg(str4, function (res) {
                                sendMsg(str6, function (res) {
                                    console.log('====>>初始发送完成')
                                    console.log('====>>打开加载框')
                                    wx.showToast({
                                        title: '正在保存数据',
                                        icon: 'loading',
                                        mask: true,
                                        duration: 10000,


                                    })
                                })

                            })
                        })
                    })
                })
            })

        } else {
            console.log('连接设备失败')
        }

    })
}

//连接设备
function connectTO(did, callback) {
    var that = this;
    // wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
    // 	success: function(res) {
    // 		console.log('连接设备前，先停止搜索周边设备:')
    // 		console.log(res)
    // 	}
    // })
    wx.showLoading({
        title: '连接蓝牙设备中...',
    })

    console.log('连接did:'+did)
    wx.createBLEConnection({ //若小程序在之前已有搜索过某个蓝牙设备，并成功建立链接，可直接传入之前搜索获取的deviceId直接尝试连接该设备，无需进行搜索操作。
        deviceId: did,
        timeout: 6000,
        success: function (res) {
            console.log('连接成功:')
            console.log(res)
            wx.hideLoading()


            callback && typeof callback === 'function' ? callback(true) : null;

        },
        fail: function (err) {
            console.log("蓝牙连接调用失败");
            wx.hideLoading()
            console.log(err)


            wx.showToast({
                title: '设备连接失败，重试中...\n若反复如此，请重启小程序或设备',
                icon: 'none',
                duration: 5000
            })

            callback && typeof callback === 'function' ? callback(false) : null;
        },
        complete: function () {
            console.log("==连接的设备ID:" + did);
        }
    })
}

var closeconnnum = 0;

function closeconn(did) {
    if (app.globalData.equconn0) {


        console.log('===>>开始断开连接')
        wx.closeBLEConnection({
            deviceId: did,
            success: function (res) {
                console.log('====>>断开连接成功')
                console.log(res)
                app.globalData.equconn0 = false
                closeconnnum = 0
            },
            fail: function (err) {
                console.log('====>>断开连接失败')
                console.log(err)
                var timeOut = setTimeout(function () {
                    console.log("====>>100")
                    if (closeconnnum < 5) {
                        closeconnnum++
                        closeconn(did)
                    }


                }, 100)

            }
        })
    }
}


//停止搜索蓝牙设备

function stopBluetoothFond() {

    console.log('停止监听蓝牙设备搜索')
    //停止监听蓝牙设备搜索
    wx.offBluetoothDeviceFound()

    console.log('停止搜索周边设备')
    wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
        success: function (res) {
            console.log('扫描结束，停止搜索周边设备:')
            console.log(res)
        }
    })

    closeBLEConnection()


}

function closeBLEConnection() {
    console.log('关闭蓝牙连接')
    wx.closeBLEConnection()
}


//===========字节转换 start=============
function updateEqu(obj) {
    let keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        app.globalData.equs[key] = obj[key]
    }

    console.log('==更新后的设备信息')
    console.log(app.globalData.equs)
}

//===========字节转换 end=============

// 获取连接设备的service服务
function getServices(did, callback) {
    var that = this;
    wx.getBLEDeviceServices({ //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备，包括已经和本机处于连接状态的设备
        // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        deviceId: did,
        success: function (res) {
            console.log('获取蓝牙设备所有服务成功：', res);
            console.log("res:"+res)
            app.globalData.services = res.services
            app.globalData.ewBluetooth.serviceUuid = res.services[0].uuid
            // that.data.services = res.services
            console.log('获取蓝牙设备所有服务成功：', app.globalData.services);
            // that.setData({
            // 	serviceId: that.data.services[0].uuid,
            // })

            console.log("额温服务uuid:", app.globalData.ewBluetooth.serviceUuid)

            wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                deviceId: did,
                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
                serviceId: app.globalData.ewBluetooth.serviceUuid, //-----注意是that.data.services[0].uuid
                success: function (res) {
                    console.log(res)
                    app.globalData.ewBluetooth.characteristics = res.characteristics
                    console.log('该设备 第一个服务的 信息: ', app.globalData.ewBluetooth)

                    // for (var i = 0; i < res.characteristics.length; i++) {
                    // app.globalData.ewBluetooth.serviceUuid = app.globalData.services[0].uuid
                    // app.globalData.ewBluetooth.characteristics.characteristicsId = res.characteristics[i].uuid
                    // app.globalData.ewBluetooth.characteristics.properties = res.characteristics[i].properties

                    // if (res.characteristics[i].properties.notify) { //注意characteristic(特征值)信息,properties对象
                    // 	that.setData({
                    // 		notifyServicweId: app.globalData.services[0].uuid,
                    // 		notifyCharacteristicsId: res.characteristics[i].uuid,
                    // 	})
                    // 	console.log("notifyServicweId:", that.data.notifyServicweId, "notifyCharacteristicsId", that.data.notifyCharacteristicsId)
                    // }
                    // if (res.characteristics[i].properties.write) {
                    // 	that.setData({
                    // 		writeServicweId: app.globalData.services[0].uuid,
                    // 		writeCharacteristicsId: res.characteristics[i].uuid,
                    // 	})
                    // 	console.log("writeServicweId:", that.data.writeServicweId, "writeCharacteristicsId", that.data.writeCharacteristicsId)
                    // } else if (res.characteristics[i].properties.read) {
                    // 	that.setData({
                    // 		readServicweId: app.globalData.services[0].uuid,
                    // 		readCharacteristicsId: res.characteristics[i].uuid,
                    // 	})
                    // 	console.log("readServicweId:", that.data.readServicweId, "readCharacteristicsId", that.data.readCharacteristicsId)
                    // }
                    // }
                },
                fail: function () {
                    console.log("获取连接设备的所有特征值：", res);
                },
                complete: function () {
                    console.log("获取服务执行完成!获取到的服务信息如下：");
                    console.log(app.globalData.ewBluetooth)

                    var b = false
                    if (app.globalData.ewBluetooth.characteristics[0].uuid != '') {
                        b = true
                    }
                    callback && typeof callback === 'function' ? callback(b) : null;
                }
            })
        }
    })
}

//发送
function sendMsg(str, callback) {
    var that = this;
    // // 这里的回调可以获取到 write 导致的特征值改变
    // wx.onBLECharacteristicValueChange(function(characteristic) {
    // 	console.log('characteristic value changed:1', characteristic)
    // })
    var timeOut = setTimeout(function () {
        console.log("====>>50")
    }, 50)
    str = str + '\n'
    console.log('====>>数据')
    console.log(str)
    if (str.length > 20) {
        let strcount = Math.ceil(str.length / 20)
        console.log('====>>分包次数：' + strcount)
        let str1 = ''
        let b = false
        for (var i = 0; i < strcount; i++) {
            console.log('==>>i===' + i)
            if (i < strcount - 1) {
                str1 = str.substr(i * 20, (i + 1) * 20)
            } else {
                str1 = str.substr(i * 20, str.length)
            }

            console.log('====>>第 ' + (i + 1) + '次发送：' + str1)

            let buffer = new ArrayBuffer(str1.length)
            let dataView = new DataView(buffer)
            for (var j = 0; j < str1.length; j++) {
                dataView.setUint8(j, str1.charAt(j).charCodeAt())
            }

            // var dataView = new DataView(buf)
            // dataView.setUint8(0, 99)
            console.log('==>>分包发送数据')
            console.log(str1)
            console.log(buffer)

            wx.writeBLECharacteristicValue({
                deviceId: app.globalData.ewBluetooth.deviceId,
                serviceId: app.globalData.ewBluetooth.serviceUuid,
                characteristicId: app.globalData.ewBluetooth.characteristics[1].uuid,
                value: buffer,
                success: function (res) {
                    console.log('发送 成功', res)
                    b = true
                },
                fail: function (err) {
                    console.log('====>>发送 失败')
                    console.log(err)
                    app.globalData.equconn0 = false
                }

            })
        }
        callback && typeof callback === 'function' ? callback(b) : null;
    } else {


        let buffer = new ArrayBuffer(str.length)
        let dataView = new DataView(buffer)
        for (var i = 0; i < str.length; i++) {
            dataView.setUint8(i, str.charAt(i).charCodeAt())
        }

        // var dataView = new DataView(buf)
        // dataView.setUint8(0, 99)
        console.log('==>>发送数据')
        console.log(str)
        console.log(buffer)


        let b = false
        wx.writeBLECharacteristicValue({
            deviceId: app.globalData.ewBluetooth.deviceId,
            serviceId: app.globalData.ewBluetooth.serviceUuid,
            characteristicId: app.globalData.ewBluetooth.characteristics[1].uuid,
            value: buffer,
            success: function (res) {
                console.log('发送 成功', res)
                b = true
            },
            fail: function (err) {
                console.log('====>>发送 失败')
                console.log(err)
                app.globalData.equconn0 = false
            },
            complete: function () {
                callback && typeof callback === 'function' ? callback(b) : null;
            }
        })

    }


}

//接收消息
function readMsg() {
    var that = this;
    // // 必须在这里的回调才能获取
    // wx.onBLECharacteristicValueChange(function(characteristic) {
    // 	let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join(
    // 		'');
    // 	console.log('===============hex')
    // 	console.log(hex)
    // })
    if (app.globalData.ewBluetooth.characteristics[0].properties.read) {
        wx.readBLECharacteristicValue({
            deviceId: app.globalData.ewBluetooth.deviceId,
            serviceId: app.globalData.ewBluetooth.serviceUuid,
            characteristicId: app.globalData.ewBluetooth.characteristics[0].uuid,
            success: function (res) {
                console.log('读取到的数据:');
                console.log(res)
                console.log(res.errMsg)
            }
        })
    } else {
        console.log('===此服务不可读')
    }
}

//监听蓝牙连接状态
function onBLEState() {
    console.log('==============启用低功耗蓝牙设备特征值变化时的 notify 功能')
    console.log(app.globalData.ewBluetooth)
    wx.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: app.globalData.ewBluetooth.deviceId,
        serviceId: app.globalData.ewBluetooth.serviceUuid,
        characteristicId: app.globalData.ewBluetooth.characteristics[0].uuid,

        success(res) {
            console.log('==============>>> 监听蓝牙notify 成功')
            console.log(res)
        },
        fail(res) {
            console.log(res, '启用低功耗蓝牙设备监听失败')
            // that.measuringTip(res)
        },
        complete(res) {
            /*用来监听手机蓝牙设备的数据变化*/
            console.log('====>>>监听数据变化最终执行')
            console.log(res)
            // wx.onBLEConnectionStateChange(function(res) {
            // 	console.log("监听蓝牙连接状态: " + JSON.stringify(res));
            // 	// 该方法回调中可以用于处理连接意外断开等异常情况
            // 	console.log(`设备： ${res.deviceId}  的连接状态: ${res.connected}`)
            // })


        }
    })


}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

function ab2Ascii(buffer) {
    var str = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return String.fromCharCode(bit);
        }
    )
    return str.join('');
}

function strToHexCharCode(str) {
    str = str + ''

    if (str === "")
        return "";
    var hexCharCode = [];
    hexCharCode.push("0x");
    for (var i = 0; i < str.length; i++) {
        hexCharCode.push((str.charCodeAt(i)).toString(16));
    }
    return hexCharCode.join("");
}

function hexCharCodeToStr(hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr =
        trimedStr.substr(0, 2).toLowerCase() === "0x" ?
            trimedStr.substr(2) :
            trimedStr;
    var len = rawStr.length;
    if (len % 2 !== 0) {
        alert("Illegal Format ASCII Code!");
        return "";
    }
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
        resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join("");
}

function ctof(temp) {

    return changeTwoDecimal_f(((Math.floor((temp * 9 / 5 + 3200) / 10)) / 10));
}

function ftoc(temp) {

    return ((temp - 32) * 5 / 9).toFixed(1);
}

function handleData(temp) {

    return changeTwoDecimal_f(((Math.floor(temp / 10)) / 10))

}

function changeTwoDecimal_f(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
        return 0;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 1) {
        s_x += '0';
    }
    return s_x;
}


